import sys
import pygame
from settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien



class AlienInvasion:

    def __init__(self):

        """初始化 pygame"""
        pygame.init()

        """创建设类的对象"""
        self.settings = Settings()

        """创建窗口对象，设置窗口的宽高"""
        self.screen = pygame.display.set_mode((
            self.settings.screen_width, self.settings.screen_height))

        self.ship = Ship(self)

        """设置窗口的标题"""
        pygame.display.set_caption("Alien Invasion")

        """创建用于存储子弹的编组"""
        self.bullets = pygame.sprite.Group()

        self.aliens = pygame.sprite.Group()
        self._create_fleet()

    def _create_fleet(self):
        """穿件一个外星人，并计算一行可容纳多少个外星人"""
        """外星人之间的间距为外星人的宽度"""
        alien = Alien(self)
        alien_width, alien_height = alien.rect.size
        alien_width = alien.rect.width
        available_space_x = self.settings.screen_width - (2 * alien_width)
        number_alien_x = available_space_x // (2 * alien_width)

        """计算屏幕可容纳多少外星人"""
        ship_height = self.ship.rect.height
        available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
        number_rows = available_space_y // (2 * alien_height)

        """创建外星人群"""
        for row_number in range(number_rows):
            for alien_number in range(number_alien_x):
                self._create_alien(alien_number, row_number)

    def _create_alien(self, alien_number, row_number):
        alien = Alien(self)

        alien_width, alien_height = alien.rect.size

        alien_width = alien.rect.width
        alien.x = alien_width + 2 * alien_width * alien_number
        alien.rect.x = alien.x

        alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number

        self.aliens.add(alien)


    def _fire_bullet(self):
        """创建一个子弹，并将其加入编组 bullets 中"""
        new_bullet = Bullet(self)
        self.bullets.add(new_bullet)

    def _update_aliens(self):
        self._check_fleet_edges()
        self.aliens.update()

    def _check_fleet_edges(self):
        """有外形人到达边缘采取措施"""
        for alien in self.aliens.sprites():
            if alien.check_edges():
                self._change_fleet_direction()
                break

    def _change_fleet_direction(self):
        """整群外星人下移"""
        for alien in self.aliens.sprites():
            alien.rect.y += self.settings.fleet_drop_speed
        self.settings.fleet_direction *= -1

    def run_game(self):

        while True:

            for event in pygame.event.get():
                 if event.type == pygame.QUIT:
                     sys.exit()

                 elif event.type == pygame.KEYDOWN:
                     if event.key == pygame.K_RIGHT:
                        self.ship.moving_right = True
                     elif event.key == pygame.K_LEFT:
                         self.ship.moving_left = True
                     elif event.key == pygame.K_SPACE:
                         self._fire_bullet()

                 elif event.type == pygame.KEYUP:
                     if event.key == pygame.K_RIGHT:
                         self.ship.moving_right = False
                     elif event.key == pygame.K_LEFT:
                         self.ship.moving_left = False

            if self.ship.moving_right and self.ship.rect.right < self.settings.screen_width:
                self.ship.rect.x += 1
            if self.ship.moving_left and self.ship.rect.x > 0:
                self.ship.rect.x -= 1

            """更新子弹的位置"""
            self.bullets.update()

            """从编组中删除消失的子弹"""
            for bullet in self.bullets.copy():
                if bullet.rect.bottom < 0:
                    self.bullets.remove(bullet)
            # print(len(self.bullets))
            collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True)

            self._update_aliens()

            """给窗口填充背景色"""
            self.screen.fill(self.settings.bg_color)
            self.ship.bltime()

            for bullet in self.bullets.sprites():
                bullet.draw_bullet()

            self.aliens.draw(self.screen)

            """每次执行时，都会基于现有条件刷新屏幕"""
            pygame.display.flip()


if __name__ == "__main__":
    ai = AlienInvasion()
    ai.run_game()
